/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var NN = require('../Poker/NN');
var PokerRoom = require('../Poker/room').PokerRoom;

var Const = require('./const');
var SubCode = require('../subCode');

var RoundStatus = {
    'WAITING': 1,   // 等待其它玩家准备
    'PREPARE': 2,    // 开始后的等待时间
    'READY': 3,     // 就绪，开始游戏
    'PLAY': 4,     // 玩家选牌
}

exports.XQNNRoom = PokerRoom.extend({
    _roundStatus: RoundStatus.WAITING,

    _dealerIndex: 0,           // 庄家坐位
    _nextDealerIndex: 0,        //下一轮庄家的位置
    selectTime: 0,        // 开始选牌的时间
    _selectMultiTime: 0,        // 选择倍数的时间

    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);

        this.baseScore = parseInt(this.getOption("baseScore"));//底分
        this.specialCard = this.getOption("specialCard");//特殊牌型
        this.fanbei = this.getOption("fanbei");

        this.selectedMulti = false;
        this.selected = false;

        this.selectedID = 0;
        this.selectedMultiID = 0;

        this.selectMultiTime = 0;
        this.selectTime = 0;

        this._dealerIndex = 0;
        this._nextDealerIndex = 0;
        this._roundStatus = RoundStatus.WAITING;
        this.MS = this.getOption("MS") == 1 ? "NNSZ" : "LLZZ";

        this.selectTime = 0;
        this._selectMultiTime = 0;

    },
    reset: function () {
        this.selectedMulti = false;
        this.selected = false;

        this.selectMultiTime = 0;
        this.selectTime = 0;

        clearTimeout(this.selectedID);
        clearTimeout(this.selectedMultiID);
    },

    onDestroy: function () {
        clearTimeout(this.selectedID);
        clearTimeout(this.selectedMultiID);
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoundInfo: function () {
        var info = this._super();
        info.curRound = this.getCurRound();
        return info;
    },

    /**
     * 获取房间配置
     */
    getRoomConfig: function () {
        return {
            'destroyWaitTime': 180,          // 申请解散房间的等待时长
            'destroySettlement': Def.DestroySettlement.YES,// 解散房间是否结算，参考Def.DestroySettlement
            'waitTimeoutTime': 0,            // 等待响应超时时长(超时将被算作强退)
            'waitTimeoutAfter': 5,           // 等待响应超时后定时时长
            'waitTimeoutTrustee': 0,         // 等待响应超时后是否托管
            'respDestroyIgnore': 0,          // 响应解散房间的忽略人数（X人房间Y人同意即可解散，忽略人数为X-Y）
            'respDestroyIgnoreOffline': 1,  // 响应解散房间是否忽略离线玩家
            'respDestroyReject': 1,          // 响应解散房间的拒绝人数（拒绝达到多少人将直接解散）
            'resetDestroyOnNewRound': 0      // 房间结算时是否重置解散房间信息
        }
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.dealer = this._dealerIndex;

        if (this.selectTime) {
            info.selectMultiTime = 0;
            info.selectCardTime = this.getHideOption("selectWaitMS") - (Date.parse(new Date()) - this.selectTime);
        } else {
            info.selectMultiTime = this.getHideOption("selectMultiWaitMS") - (Date.parse(new Date()) - this.selectMultiTime);
            info.selectCardTime = this.getHideOption("selectWaitMS");
        }
        return info;
    },

    onAfterPlayerReady: function (player) {
        this._super(player);

        var subConfig = this.getSubConfig();
        //检查是否开始游戏
        if (!this.isPlaying() && this.getReadyPlayerCount() >= subConfig.roomPlayerMin && this.getPlayerCount() == this.getReadyPlayerCount()) {

            var creator = this.getPlayerByUid(this.getCreator());
            var enableStart = (creator && creator.isReady()) ? true : false;

            if (enableStart) {
                this._roundStatus = RoundStatus.READY;
                this.tryStartNewRound();
            }
        }
    },

    checkStartNewRound: function () {
        if (this.isPlaying()) {
            return false;
        }

        if (this._roundStatus != RoundStatus.READY) {
            return false;
        }

        return true;
    },
    //1
    onBeforeStartNewRound: function () {
        this._super();
        if (this._dealerIndex == 0) {
            var nums = this.getReadyPlayerCount();
            var dealIndex = Math.floor(Math.random() * nums) + 1;
            var validIndex = 0;
            for (var i = 0; i < dealIndex; ++i) {
                validIndex = this.getNextPlayer(validIndex);
            }

            this._nextDealerIndex = validIndex;
            var randoms = [];

            this.enumPlayers(function (eIndex, ePlayer) {
                randoms.push(eIndex);
            });
        }
    },
    //2
    onAfterStartNewRound: function () {
        this._super();
        this._startPlay();
    },

    onSettlement: function () {
        this._super();

        this.enumPlaying(function (eIndex, ePlayer) {
            ePlayer.settlementPattern();
        });
    },

    onCurRoundFinished: function () {
        this._super();
        this._roundStatus = RoundStatus.WAITING;
        if (this.MS == "NNSZ") {
            var maxNiu = {
                "index": this._dealerIndex,
                "maxNum": 301
            }
            var Nius = [];
            this.enumPlayers(function (eIndex, ePlayer) {
                if (ePlayer._stat.roundPattern == Const.Pattern.NN) {
                    Nius.push(eIndex);
                    if (NN.cardLT(ePlayer._getMaxCard(), maxNiu["maxNum"])) {
                        maxNiu["maxNum"] = ePlayer._getMaxCard();
                        maxNiu["index"] = eIndex;
                    }
                }
            });

            this._nextDealerIndex = maxNiu["index"];
        }
        if (this.MS == "LLZZ") {
            if (this._dealerIndex < 1 || this._dealerIndex > this.getMaxPlayer()) {
                this._dealerIndex = 1;
            }
            var tmpIndex = this._dealerIndex;
            do {
                tmpIndex = this.getNextIndex(tmpIndex);
                var tmpPlayer = this.getPlayerByIndex(tmpIndex);
                if (tmpPlayer) {
                    break;
                }
            } while (tmpIndex != this._dealerIndex);

            this._nextDealerIndex = tmpIndex;
        }
        this.reset();
    },

    /******************************************************************
     * 功能接口
     ******************************************************************/

    handleSelectMulti: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING});
            return;
        }

        if (!msg.hasOwnProperty("multi") || isNaN(msg.multi)) {
            callback({code: Code.ARGS_INVALID});
            return;
        }

        var multi = parseInt(msg.multi);
        if (multi != 5 && multi != 1 && multi != 2 && multi != 3 && multi != 4) {
            callback({code: Code.ARGS_VALUE_WRONG});
            return;
        }

        player.setMulti(multi);
        this.broadcast("onPlayerSelectedMulti", {
            playerIndex: player.getIndex(),
            multi: multi
        });
        callback({});

        var isAllSet = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (eIndex == this._dealerIndex) {
                ePlayer.setMulti(1);
            }
            if (ePlayer.getMulti() == 0) {
                isAllSet = false;
            }
        }.bind(this));

        if (isAllSet) {
            this.initPlayersHandCards();
            this._waitSelectCards();
        }
    },

    handleSelectCards: function (player, msg, callback) {
        if (!msg.cards) {
            callback({code: Code.ARGS_INVALID});
            return;
        }

        if (!player.isPlaying()) {
            callback({code: Code.PLAYER_NOT_PLAYING});
            return;
        }

        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING});
            return;
        }

        if (this.isCurRoundFinished()) {
            callback({code: Code.ROOM_ROUND_FINISHED});
            return;
        }

        var cards = msg.cards;
        if (!ExObject.isArray(cards)) {
            callback({code: Code.ARGS_VALUE_WRONG});
            return;
        }

        if (!player.setSelectedCards(cards)) {
            callback({code: SubCode.CARD_NOT_EXIST});
            return;
        }

        callback({});

        var pattern = player._calcNiu();
        this.broadcast("onPlayerSelectCards", {
            playerIndex: player.getIndex(),
            selectCard: player._selectedCards,
            pattern: pattern,
            handCard: player._handCards.getInitCards()
        });

        player.isSelected = true;

        var isAllSelected = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isSelectedCards()) {
                isAllSelected = false;
            }
        });

        if (isAllSelected && this.selected == false) {
            this.selected = true;
            this.settlementCurRound();
        }
    },

    _startPlay: function () {
        if (this._nextDealerIndex != 0) {
            this._dealerIndex = this._nextDealerIndex;
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
        } else {
            this._dealerIndex = 1;
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
        }
        if (this.MS == "LLZZ" || this.MS == "NNSZ") {
            if (this.getCurRound() == 1) {
                setTimeout(function () {
                    this._waitSelectMulti();
                }.bind(this), this.getHideOption("startWaitMS"));
            } else {
                this._waitSelectMulti();
            }
        }
    },

    _waitSelectCards: function () {
        if (this.selectedMulti) {
            return;
        }
        this.selectedMulti = true;
        this._roundStatus = RoundStatus.PLAY;
        this.selectTime = Date.parse(new Date());
        this.selectedID = setTimeout(function () {
            if (this.selected) {
                return;
            }
            this.selected = true;
            this.settlementCurRound();
        }.bind(this), this.getHideOption("selectWaitMS"));
    },

    _waitSelectMulti: function () {
        this.broadcastReplay("onSelectTime", {
            selectMultiTime: this.getHideOption("selectMultiWaitMS"),
            selectCardTime: this.getHideOption("selectWaitMS")
        });
        this.selectMultiTime = Date.parse(new Date());
        this.selectedMultiID = setTimeout(function () {
            if (!this.isPlaying()) {
                return;
            }

            if (this._roundStatus != RoundStatus.READY) {
                return;
            }

            this.enumPlaying(function (eIndex, ePlayer) {
                if (ePlayer.getMulti() == 0) {
                    ePlayer.setMulti(1);
                    this.broadcast("onPlayerSelectedMulti", {
                        playerIndex: ePlayer.getIndex(),
                        multi: ePlayer.getMulti()
                    });
                }
            }.bind(this));
            this.initPlayersHandCards();
            this._waitSelectCards();

        }.bind(this), this.getHideOption("selectMultiWaitMS"));
    },
});